import React, { useEffect, useState } from 'react';
import { ChatStore } from "../../store/ChatStore";
import { MainStore } from "../../store/MainStore";
import { inject, observer, Observer } from 'mobx-react';
import "./QuickMessage.less"
import { Icon, Spin } from 'antd';
import Modal from 'antd/es/modal';
import TextArea from 'antd/es/input/TextArea';
import { AutoSizer, List } from 'react-virtualized';
import imsdk from '../../net/IMSDK';
import { Pagination,ConfigProvider,Button } from 'antd';
import zhCN from 'antd/es/locale/zh_CN';

export type IQuickMessagesProps = {
  onDialogShow?:()=>void
  onClickMessage?:(message:string)=>void
}
export type IQuickMessagesState = {
  messages:Array<{id:number,content:string}>,
  loading:boolean,
  msgCount:number,
  pageIndex:number,
  pageSize:number,
  msgTip:string,
  refreshLoading:boolean,
  currentMessage:{id:number,content:string},
  showEdit:boolean
  dialogMode:'edit'|'add',
  fastMsgArea:{top:string,right:string,txt:string}
}

@inject('chatStore')
@observer
export default class QuickMessage extends React.Component<IQuickMessagesProps, IQuickMessagesState> {
  state: Readonly<IQuickMessagesState> = {
    dialogMode:'edit',
    showEdit:false,
    currentMessage:{content:'',id:-1},
    loading:true,//列表所有相关内容全部等loading渲染
    messages:[],
    msgCount:1,
    pageIndex:1,
    pageSize:10,
    msgTip:'没有内容',
    refreshLoading:false,
    fastMsgArea:{
      top:'100%',
      right:'100%',
      txt:''
    }
    // messages:[
    //   {
    //     id:0,
    //     content:`您好，很高兴为您服务，请问有什么可以帮到您的吗？`
    //   },
    //   {
    //     id:1,
    //     content:`非常抱歉给您带来了困扰，我们会尽快解决您的问题！`
    //   },{
    //     id:2,
    //     content:`我们非常理解您的心情，会尽快处理的！`
    //   },{
    //     id:3,
    //     content:`您对客服的服务还满意吗?`
    //   },{
    //     id:4,
    //     content:`亲爱的，您的申请已经在处理，请稍等！`
    //   }
    // ]
  }
  get injected() {
    return this.props as IQuickMessagesProps;
  }
  onAddMessage = ()=>{
    // if( this.props.onDialogShow ){
    //   this.props.onDialogShow()
    // }
    this.setState({
      dialogMode:'add',
      showEdit:true,
      currentMessage:{id:-1,content:''}
    })
  }
  addMessageHandle=async ()=>{
    // this.props.onDialogShow()
    // //console.log('addMessageHandle')
    // //console.log('this.state.currentMessage.content',this.state.currentMessage.content)

    const content = this.state.currentMessage.content.trim()
    if (content.length==0) { //空字符串
      return
    }

    const response =await imsdk.createCommonText(this.state.currentMessage.content)
    // //console.log('addMessageHandle response',response)
    if (response.resultCode == 1) { //添加成功
      // //console.log("this.state.pageIndex",this.state.pageIndex)
      await this.pageChange(0,this.state.pageSize)
      this.setState({
        showEdit:false,
        currentMessage:{id:-1,content:''},
        pageIndex:1
      })
    }
  }
  editMessageHandle= async()=>{
    // //console.log('editMessageHandle',this.state.currentMessage)
    const content = this.state.currentMessage.content.trim()
    if (content.length==0) { //空字符串
      return
    }
    
    const response =await imsdk.modifyCommonText(this.state.currentMessage.id.toString(),this.state.currentMessage.content)
    if (response.resultCode == 1) { //编辑成功
      await this.pageChange(0,this.state.pageSize)
      this.setState({
        showEdit:false,
        currentMessage:{id:-1,content:''},
        pageIndex:1
      })
    }
  }
  onEditMessage = (item)=>{
    // if( this.props.onDialogShow ){
    //   this.props.onDialogShow()
    // }
    this.setState({
      dialogMode:'edit',
      showEdit:true,
      currentMessage:item
    })
  }
  onRemoveMessage =async (item)=>{
    // //console.log('onRemoveMessage',item)
    const response =await imsdk.removeCommonText(item.id.toString())
    // //console.log('onRemoveMessage response',response)
    if (response.resultCode == 1) { //删除成功
      this.setState({
        messages:this.state.messages.filter(_item=>_item.id != item.id)
      })
    }
  }
  onSendMessage = (item)=>{
    if( this.props.onClickMessage ){
      this.props.onClickMessage(item.content)
    }
  }

  // 组件挂载DOM后调用，生命周期
  componentDidMount() {
    this.fetchMessages();
  }

  async fetchMessages() {
    try {
      const re = await imsdk.listCommonText(this.state.pageIndex-1,this.state.pageSize);
      console.log("观察re",re)
      // debugger
      // //console.log('调用到了',re,re.data)
      const response = re.data;
      if(response.data.length==0){
        this.setState({
          loading:false,
          msgTip:'内容为空'
        })
        return
      }

      this.setState({ 
        messages:response.data.map((item)=>({
          id:item.id,
          content:item.content
        })),
        msgCount:response.count,
        // messages: [], //假如没有内容
        loading:false,
      });
    } catch (error) {
      console.log("观察re 抛出错误",error)
      // //console.error('调用到了 出错 Failed to fetch messages:', error);
      this.setState({
        loading:false,
        msgTip:'网络故障请刷新'
      })
    }
  }

  pageChange=async (page, pageSize)=>{
    // //console.log('pageChange这里',page, pageSize)
    this.setState({
      messages: [], 
      loading:true,
      pageIndex:page
    })
    const re = await imsdk.listCommonText(page-1,pageSize);
    const response = re.data;
    this.setState({ 
      messages:response.data.map((item)=>({
        id:item.id,
        content:item.content
      })),
      msgCount:response.count,
      loading:false,
    });
  }
  
  render() {
    return (
      <>
      <div style={{top:this.state.fastMsgArea.top,right:this.state.fastMsgArea.right}} className='fastMsg'>
      {this.state.fastMsgArea.txt}
      </div>
      <Modal
        zIndex={9999}
        title={this.state.dialogMode == 'edit'?'编辑':'添加'}
        visible={this.state.showEdit}
        okText={this.state.dialogMode == 'edit'?'保存':'添加'}
        cancelText="取消"
        onCancel={() => {
          this.setState({
            showEdit:false
          })
        }}
        onOk={() => {
          if( this.state.dialogMode == 'edit' ){
            // //console.log("onok这里")
            this.editMessageHandle()
            return
            this.setState({
              messages:this.state.messages.map(item=>{
                if( item.id == this.state.currentMessage.id ){
                  return {
                    ...item,
                    content:this.state.currentMessage.content
                  }
                }
                return item
              })
            })
          }else{
            // //console.log("onok这里")
            this.addMessageHandle()
            return
            
          }
          this.setState({
            showEdit:false
          })
        }}
        >
          <TextArea rows={4} value={this.state.currentMessage.content} onChange={(evt)=>{
           
            this.setState({
              currentMessage:{
                ...this.state.currentMessage,
                content:evt.target.value
              }
            })
          }}  />
        </Modal>
      <div className='quick-message-wrapper'>
      
            {
          this.state.loading ? (
            <div className='loading-box'><Spin></Spin></div>
          ):
          (
            this.state.messages.length == 0
            ?(<div className='loading-box'>{this.state.msgTip}<Button style={{marginLeft:'10px'}} size='small' onClick={async()=>{
              this.setState({
                refreshLoading:true
              })
              await this.fetchMessages()
              setTimeout(()=>{
                this.setState({
                  refreshLoading:false
                })
              },1000)
            }} type="primary" loading={this.state.refreshLoading}>刷新</Button></div>)
            :( <div className='message-list'>
              <div style={{width:'100%',height:'100%'}}>
                            { 
                            this.state.messages.map((item,index)=>{
                              return (
                                <div key={index} className="item">
                                  <div onMouseOut={()=>{
                                    //console.log("移出")
                                    this.setState({
                                      fastMsgArea:{
                                        top:'100%',
                                        right:'100%',
                                        txt:''
                                      }
                                    })
                                  }} onMouseOver={(event) =>{
                                    const rect = event.currentTarget.getBoundingClientRect();
                                    if (item.content.length > 37) {
                                      this.setState({
                                        fastMsgArea:{
                                          top:`${rect['y']+rect['height']}px`,
                                          right:`${window.innerWidth - rect['right']}px`,
                                          txt:item.content
                                        }
                                      })
                                    }
                                  }} onClick={()=>{
                                    this.onSendMessage(item)
                                  }} className='item-txt' >{item.content}</div>
                                  <span className='btns'>
                                  <Icon type="edit" onClick={()=>this.onEditMessage(item)}/>
                                  <Icon type="delete" onClick={()=>this.onRemoveMessage(item)} style={{marginLeft:'10px'}}/>
                                  </span>
                                  
                                </div>
                              )
                            })
                          }
                          </div>
              
            </div>)
          )
        }
        
       

        <div className='message-list-title'>常用语(共{this.state.msgCount}条,每页{this.state.pageSize}条)点击直接发送:</div>
      <ConfigProvider locale={zhCN}>
              <Pagination simple current={this.state.pageIndex} total={this.state.msgCount} onChange={this.pageChange} pageSize={this.state.pageSize}/>
            </ConfigProvider>
        
       

        <div className="message-footer">
          <div className="btn btn-add" onClick={()=>{
            this.onAddMessage()
          }}>
            <img src={require('./../../assets/image/icon-add.png')}  />
            <span>添加</span>
          </div>
          {/* <div className="btn btn-add">
            <img src={require('./../../assets/image/icon-add.png')}  />
            <span>编辑</span>
          </div> */}
        </div>
      </div>

      </>
    );
  }
}
